import React, {useEffect, useState} from 'react';
import jsonMoney from '../../axios/Money.json'
import axios from 'axios';

const moneyList = jsonMoney.data

function Rightcol({dataMoney,setDataMoney}) {
    // 创建form-data
    // const formData = new FormData();
    const [error, setError] = useState(null);
    const userDTOId = JSON.parse(localStorage.getItem("userDTOId"))
    useEffect(() => {
        if(userDTOId.id){
        axios.get(`http://localhost:8091/user/money/${userDTOId.id}`)
            .then((response) => {
                // console.log(response.data)
                setDataMoney(response.data.data);
                setError(null);
            })
            .catch(error => {
                // window.location = "/login"
                setError(error);
                alert(error)
                alert("请登录")
            });
        } else {
            // 处理userId不存在的情况
            setError("用户数据未找到");
        }
    }, []);
    // 使用数据渲染组件
    return <div className="rightcol ">
        <div className="block_header">您的 雪球 帐户</div>
        <div className="wallent_actions_ctn shadow-sm p-3 mb-5 bg-white rounded">
            <div className='clearfix'>
                <div style={{float: "left"}}>当前钱包余额</div>
                <div style={{float: "right"}}>¥ {dataMoney} </div>
            </div>
            <div><a className="addfunds_linkbar linkbar text-decoration-none" href="#">查看我的帐户明细</a><br/></div>
            <div><a className="addfunds_linkbar linkbar text-decoration-none" href="#">兑换 雪球 礼物卡</a></div>
        </div>
        <div className="shadow-sm p-3 mb-5 bg-body-tertiary rounded"
             style={{border: "1px solid #ccc!important", padding: "14px;border-radius: 16px!important",}}>
            <p className="text-dark text-lg-start ">
                <img style={{maxHeight: 800}} src="/img/cx.webp" className="d-block w-100" alt=""/>
            </p>
        </div>
    </div>
}

function Leftcol({dataMoney,setDataMoney}) {
    useEffect(() => {
        const userDTOId = localStorage.getItem("userDTOId");
        if (userDTOId !== null) {
            try {
                const userDTO = JSON.parse(userDTOId);
                if (!userDTO.username || userDTO.username.trim() === "") {
                    // 用户名不存在或为空，重定向到登录页面
                    window.location.href = "/login";
                }
            } catch (e) {
                // 解析JSON时出错，可能是无效的JSON格式，重定向到登录页面
                console.error("userDTOId无效的JSON格式, 重定向到登录页面:", e);
                window.location.href = "/login";
            }
        } else {
            // userDTOId不存在，重定向到登录页面
            window.location.href = "/login";
        }
    }, []); // 空数组表示这个effect只会在组件挂载后运行一次
    // 假设我们已经重定向或者用户已登录，继续渲染页面
    const username = localStorage.getItem("userDTOId") !== null
        ? JSON.parse(localStorage.getItem("userDTOId")).username
        : ''; // 如果没有用户名，则默认为空字符串
    return <div className="leftcol ">
        <h2 className="addfunds_pageheader"> 为 {username}  的钱包充值</h2>
        <div className="addfunds_about leftcol">
            <div>您的 雪球 钱包资金可用于购买 雪球商城 上的任何一项商品。</div>
            <div className='text-black-50'>下订单之前，您有机会检查您的订单。</div>
        </div>
        <div className="d-flex flex-column bd-highlight mb-3" id="prices_user">
            {moneyList.map(item => {
                return <div className="p-2 bd-highlight shadow-sm p-3 mb-5 bg-white rounded">
                    <div className="addfunds_purchase_action game_purchase_action" style={{float: "right"}}>
                        <span className='text-black-50'> ¥ {item.price}</span>
                        <a className="btnv6_green_white_innerfade btn_medium" href="#" onClick={
                            () => {
                                axios.get(`http://localhost:8091/user/money?money=${item.price}
                                &id=${JSON.parse(localStorage.getItem("userDTOId")).id}`)
                                    .then((response) => {
                                        setDataMoney(response.data.data);
                                         alert("充值成功")
                                    })
                                    .catch(error => {
                                    }, []);
                            }}><span>充值</span></a>
                    </div>
                    <h1>充值 ¥ {item.price}</h1>
                </div>
            })}
        </div>
        <div className="addfunds_footer">
            <p>更多详情，请参阅<a className='text-decoration-none' href="#" rel="">《雪球 订户协议》</a>。</p>
        </div>
    </div>
}

export default function Money() {
    const [dataMoney, setDataMoney] = useState(null);
    return (<div className='Money'>
        <div class="container text-body" style={{textAlign: "start"}}>
            <div class="row">
                <div class="col-sm-8"> {/* 主体 */}
                    <Leftcol dataMoney={dataMoney} setDataMoney={setDataMoney}/>
                </div>
                <div class="col-sm-4"> {/* 右边栏 */}
                    <Rightcol dataMoney={dataMoney} setDataMoney={setDataMoney}/>
                </div>
            </div>
        </div>
    </div>)
}
